// 查找字符串，先判断输入的是 变量名、颜色名 如果是颜色以
var searchText = "";
// 定义生成表格的字符串对象
var tableJSON = {};
$(document).ready(function () {
  // 生成模式相关代码
  createMode();
  // 初始化下拉
  initSelect();
  // 初始化查询
  initSearch();
});
/**
 * 初始化查询相关
 */
function initSearch() {
  // 查询类型
  $("#fbdocsSearchType").on('changeSearchType', function (ev, currentType) {
    // 清空
    clearSearchResult();
  });
  // 查询清空按钮
  $("#clearSearch").on('click', function (ev) {
    ev.stopPropagation();
    clearSearchResult();
  });
  // 显示隐藏清空按钮
  $("#searchText").on('change', function (ev) {
    if ($(this).val()) {
      $("#clearSearch").css('display', 'block');
    } else {
      $("#clearSearch").css('display', 'none');
    }
  });

  // 查询按钮
  $("#searchBtn").on('click', function (ev) {
    ev.stopPropagation();
    let searchText = $("#searchText").val().toLowerCase();
    // 查询正则
    var searchRe;
    var searchResult = [];
    // 如果是颜色，先去找变量
    if (currentSearchType == 'color') {
      // 颜色集合
      searchRe = new RegExp(searchText, 'g');
      let currentColors = themesColor;
      // searchResult记录符合的变量
      for (let colorVar in currentColors) {
        if (searchRe.test(currentColors[colorVar].toLowerCase())) {
          searchResult.push(colorVar);
        }
      }

    } else if (currentSearchType == 'clsname') {
      searchText = searchText.replace('.', '');
      searchRe = new RegExp(searchText, 'g');
    }
    // 如果是样式，直接去查询
    $(".create-fbdocs-table").each(function (index, el) {
      var findInTable = false;
      $(el).find("tbody tr").each(function (nIndex, nTr) {
        //-----------------------------------------------------没有排除样式名的影响
        if (currentSearchType == 'clsname') {
          // 查询样式
          if (searchRe.test($(nTr).find('.flag-clsname').text())) {
            $(nTr).addClass('fd-state-selected');
            findInTable = true;
          }
        }
        if (currentSearchType == 'color') {
          let len = searchResult.length;
          for (var k = 0; k < len; k++) {
            if ($(nTr).find('.flag-color').eq(0).length > 0 && $(nTr).find('.flag-color').eq(0).data('colorVariables').indexOf(searchResult[k]) > -1) {
              $(nTr).addClass('fd-state-selected');
              findInTable = true;
              break;
            }
          }
        }
      });
      if (!findInTable) {
        $(el).parents('.fbdocs-detail-wrapper').css('display', 'none');
      }
    });
  });

}
/**
 * 初始化下拉
 */
function initSelect() {
  // 生成主题配置相关代码
  $("#fbdocsSelectTheme").on('changeTheme', function (ev, themeCode) { //
    currentTheme=themeCode;
    let newCSSLink = `./css/themes/${currentTheme}/farris-pub.css`;
    loadCSS(newCSSLink, function () {
      // 重新获取CSS中变量
      getThemesColorFromVariables();
      // 重新构造Table字符串
      createTableByRelation(colorRelation);
      // 重新生成
      $(".create-fbdocs-table").each(function (index, el) {
        let createType = $(el).data('type');
        if (tableJSON.hasOwnProperty(createType)) {
          $(el).html(tableJSON[createType]);
        }
      });
    });
  });
  // 创建主题下拉
  createSelect("fbdocsSelectTheme", themeSettings[currentMode], currentTheme, function (type) {
    currentTheme = type;
    $("#fbdocsSelectTheme").trigger("changeTheme", currentTheme);
  });
  // 创建查询类型下拉
  createSelect("fbdocsSearchType", searchTypeSettings, currentSearchType, function (type) {
    currentSearchType = type;
    $("#fbdocsSearchType").trigger("changeSearchType", currentSearchType);
  });

}

/**
 * 定义下拉插件
 */
$.fn.pubSelect = function (afterSelectFunc) {
  var defaults = {
    activeCls: ".fd-state-selected",
    groupCls: ".item-grouped",
  };
  this.each(function () {
    let selectWrap$ = $(this);

    $(selectWrap$).find('.fbdocs-select').on('click', function (e) {
      $(this).next('.fbdocs-dropdown').fadeIn();
    });
    $(selectWrap$).find(".fbdocs-dropdown").on('mouseleave', function (e) {
      $(this).fadeOut();
    });
    $(selectWrap$).find(".list-group-item").on("click", function (e) {
      if ($(this).is(defaults.groupCls) || $(this).data('type') == currentTheme) {
        return;
      }
      $(this).siblings().removeClass(defaults.activeCls).end().addClass(defaults.activeCls);
      $(selectWrap$).find('.fbdocs-select').text($(this).text());
      $(this).parents('.fbdocs-dropdown').fadeOut();
      if (afterSelectFunc) {
        afterSelectFunc($(this).data('type'));
      }
    });
  });
};

// 生成模式
function createMode() {
  let modeStr = '';
  $.each(modeSettings, function (index, item) {
    modeStr += `<div class="mode--item ${item['value'] == currentMode ? 'fb-state-selected' : ''}" data-type="${item['value']}"><span>${item['name']}</span></div>`;
  });
  $("#fbdocsMode").html(modeStr);
  $("#fbdocsMode").find('.mode--item').on('click', function (e) {
    e.stopPropagation();
    if ($(this).data('type') == currentMode) {
      return;
    }
    $(this).siblings().removeClass('fb-state-selected').end().addClass('fb-state-selected');
    // 当前模式变更
    currentMode = $(this).data('type');
    currentTheme = '';
    // 重新加载主题
    createSelect("fbdocsSelectTheme", themeSettings[currentMode], currentTheme, function (type) {
      currentTheme = type;
      $("#fbdocsSelectTheme").trigger("changeTheme", currentTheme);
    });
  });
}


/**
 * 假定data的结构最多两层
 * 生成下拉
 */
function createSelect(selectId, datas, currentVal, afterSelectFunc) {
  let selectedInfo = null;
  let selectStr = '';
  $.each(datas, function (index, item) {
    if (typeof item['value'] == 'string') {
      /**
       * 如果当前值为空，则第一项为选中项；
       * 如果当前值不为空，则相等项为选中项；
       */
      if (!selectedInfo) {
        if (currentVal != '') {
          selectedInfo = item['value'] == currentVal ? item : null;
        } else {
          currentVal = item['value'];
          selectedInfo = item;
        }
      }
      //是否有分组
      selectStr += `<li class="list-group-item ${selectedInfo && selectedInfo['value'] == item['value'] ? 'fd-state-selected' : ''}" data-type="${item['value']}">${item['name']}</li>`;
    } else {
      selectStr += `<li class="list-group-item item-grouped">${item['name']}</li>`;
      $.each(item['value'], function (nIndex, nItem) {
        if (!selectedInfo) {
          if (currentVal != '') {
            selectedInfo = nItem['value'] == currentVal ? nItem : null;
          } else {
            currentVal = nItem['value'];
            selectedInfo = nItem;
          }
        }
        selectStr += `<li class="list-group-item ${selectedInfo && selectedInfo['value'] == nItem['value'] ? 'fd-state-selected' : ''}" data-type="${nItem['value']}">${nItem['name']}</li>`;
      });
    }
  });
  let completeStr = `<div class="fbdocs-select">${selectedInfo['name']}</div>`;
  completeStr += `<div class="fbdocs-dropdown"><ul class="list-group">${selectStr}</ul></div>`;
  $("#" + selectId).html(completeStr);
  $("#" + selectId).pubSelect(afterSelectFunc);

  if(selectId=='fbdocsSelectTheme'){
    $("#fbdocsSelectTheme").trigger("changeTheme", currentVal);
  }
}

// 根据颜色关系生成Table
function createTableByRelation(colorRelation) {
  for (let propType in colorRelation) {
    // 构造结果
    // 类型
    tableJSON[propType] = `<table class="fbdocs-table"><thead> 
        <th>样式名</th>
        <th>变量</th>
        <th>色值</th>
        <th style="width:260px">状态</th>
    </thead><tbody>`;

    let propValue = colorRelation[propType];
    for (let actionType in propValue) {
      //交互类型对应的属性值
      let actionValue = propValue[actionType];
      if (actionState.hasOwnProperty(actionType)) {
        tableJSON[propType] += `<tr><td colspan="4">${actionState[actionType]}</td></tr>`;
      } else {
        tableJSON[propType] += `<tr><td colspan="4">${actionType}</td></tr>`;
      }

      for (let code in actionValue) {
        tableJSON[propType] += `<tr>`;
        // 构造样式名
        let clsName = `.fd-${propType}-${actionType}-${code}`;
        tableJSON[propType] += `<td class="flag-clsname">${clsName}</td>`;
        // 编号对应的属性值
        let codeValue = actionValue[code];
        let colorTdStr = ``;
        if (typeof codeValue == 'string') {
          // 对应的是 $f-theme-03 这样的值
          // 获取颜色
          colorTdStr += `<td>` + getCSSVariableFromFVariable(codeValue) + `</td>`;
          colorTdStr += `<td  class="flag-color" data-color-variables="${codeValue}"><div class="fp-docs-demo-wrapper">${themesColor[codeValue]}`;
          colorTdStr += _getDemo(themesColor[codeValue]) + `</div></td><td></td>`;

        } else {
          // 对应的是 "cursor": ["$f-theme-03", "$f-theme-05", "$f-theme-01"]
          let realKey = Object.keys(codeValue)[0];
          let colorStr = codeValue[realKey].join(',');
          colorTdStr += `<td>` + getCSSVariableFromFVariable(codeValue[realKey][0]) + `</td>`;
          colorTdStr += `<td><div class="fp-docs-demo-wrapper">${themesColor[codeValue[realKey][0]]}`;
          colorTdStr += _getDemo(themesColor[codeValue[realKey][0]]) + `</div></td>`;
          colorTdStr += `<td class="flag-color" data-color-variables="${colorStr}">`;
          let colorStrArray = '';
          $.each(codeValue[realKey], function (index, val) {
            colorStrArray += `<div class="fp-docs-demo-wrapper">`;
            colorStrArray += actionState[realKey][index] + '：<span style="margin:0 6px;">' + getCSSVariableFromFVariable(val) + '</span><span  style="margin:0 6px;">' + themesColor[val] + "</span>";
            colorStrArray += _getDemo(themesColor[val]);
            colorStrArray += `</div>`;
          });

          colorTdStr += colorStrArray + `</td>`;
        }
        tableJSON[propType] += colorTdStr + `</tr>`;
      }
    }
    tableJSON[propType] += `</tbody></table>`;
  }
}
/**
 * 获取颜色示例
 * @param {*} color 
 */
function _getDemo(color) {
  return `<span class="fp-docs-demo" style="background:${color}"></span>`;
}

/**
 * 清空查询结果
 */
function clearSearchResult() {
  searchText = '';
  $("#searchText").val('');
  $(".create-fbdocs-table").each(function (index, el) {
    $(el).find("tbody tr").removeClass("fd-state-selected");
    $(el).parents('.fbdocs-detail-wrapper').css('display', 'block');
  });
}
